package com.ruoyi.deepSeek;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.deepSeek.DTO.*;
import com.ruoyi.system.domain.DsLt;
import com.ruoyi.system.domain.DsXx;
import com.ruoyi.system.service.IDsLtService;
import com.ruoyi.system.service.IDsXxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Anonymous
@RequestMapping("/deepSeek")
public class DeepSeekApiController {

    @Autowired
    private DeepSeekApiService deepSeekApiService;

    @Autowired
    private IDsXxService dsXxService;

    @Autowired
    private IDsLtService dsLtService;

    // 发送对话消息接口，返回 SseEmitter 实现 SSE
    @PostMapping("/sendMessage")
    @PreAuthorize("@ss.hasPermi('deepSeek:sendMessage:add')")
    public SseEmitter sendMessage(@RequestBody RequestData requestData) {
        String user = requestData.getUser();
        String query = requestData.getQuery();
        String responseMode = requestData.getResponseMode();
        String conversationId = requestData.getConversationId();
        Long classId = requestData.getClassId();
//        DsXx dsXx = new DsXx();
//        dsXx.setXxContent(query);
//        dsXx.setRole("user");
//        dsXx.setClassId(requestData.getClassId());
//        dsXx.setUserName(user);
//        dsXx.setLtId(requestData.getConversationId());
//        dsXx.setCreateBy(user);
//        dsXx.setCreateTime(DateUtils.getNowDate());
//        dsXxService.insertDsXx(dsXx);
        System.out.println("Sending message to HttpClient: " + user + ", " + query + ", " + responseMode);

        // 直接返回 SseEmitter，Spring 会自动管理响应流
        return deepSeekApiService.sendChatMessage(user, query, conversationId, responseMode, classId);
    }

    // 发送对话消息
//    @PostMapping("/sendMessage")
//    public void sendMessage(@RequestBody RequestData requestData, HttpServletResponse response) {
//        try {
//            String user = requestData.getUser();
//            String query = requestData.getQuery();
//            String responseMode = requestData.getResponseMode();
//            String conversationId = requestData.getConversationId();
//
//            response.setContentType("text/event-stream"); // 设置响应类型为流
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("Cache-Control", "no-cache");
//            response.setHeader("Connection", "keep-alive");
//            response.setHeader("Transfer-Encoding", "chunked"); // 设置分块传输
//
//            System.out.println("Sending message to HttpClient: " + user + ", " + query + ", " + responseMode);
//
//            // 让连接保持打开，直到所有数据传输完
//            deepSeekApiService.sendChatMessage(user, query, conversationId, responseMode, response.getOutputStream());
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 如果发生错误，设置HTTP状态码为500
//        }
//    }

    // 文件上传，使用 @RequestBody 接收 JSON 数据
    @PostMapping("/uploadFile")
    @PreAuthorize("@ss.hasPermi('deepSeek:uploadFile:add')")
    public String uploadFile(@RequestBody FileUploadRequest request) {
        try {
            // 通过请求体中的数据调用 Service 层
            return deepSeekApiService.uploadImage(request.getUser(), request.getFilePath());
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 获取会话历史消息
    @PostMapping("/getMessages")
    @PreAuthorize("@ss.hasPermi('deepSeek:getMessages:list')")
    public String getMessages(@RequestBody GetMessagesRequest request) {
        try {
            return deepSeekApiService.getMessages(request.getUser(), request.getConversationId(), request.getFirstId(), request.getLimit());
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 获取会话列表
    // 获取会话列表
    @PostMapping("/getConversations")
    @PreAuthorize("@ss.hasPermi('deepSeek:getConversations:list')")
    public String getConversations(@RequestBody GetConversationsRequest request) {
        try {
            // 从Dify获取原始会话列表
            String difyResponse = deepSeekApiService.getConversations(request.getUser(), request.getLastId(), request.getLimit());

            // 将Dify返回的JSON字符串转换为对象
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode difyResponseJson = objectMapper.readTree(difyResponse);

            // 获取会话数据数组
            ArrayNode conversationsArray = (ArrayNode) difyResponseJson.get("data");

            // 从数据库获取所有聊天记录
            DsLt queryParam = new DsLt();
            queryParam.setUserName(request.getUser());  // 根据请求中的用户ID筛选
            List<DsLt> dbRecords = dsLtService.selectDsLtList(queryParam);

            // 创建一个转换映射，key是conversion_id（Dify的id），value是对应的class_id
            Map<String, Integer> conversionIdToClassIdMap = new HashMap<>();
            for (DsLt record : dbRecords) {
                // 假设conversion_id在数据库中存的可能是int类型，需要转为字符串
                if (record.getClassId() == null) {
                    return "未选择课程，本次会话将不被记录";
                }
                Integer classId = record.getClassId().intValue();

                conversionIdToClassIdMap.put(String.valueOf(record.getConversationId()), classId);
            }

            // 创建新的会话数组，仅包含在数据库中有记录的会话
            ArrayNode filteredArray = objectMapper.createArrayNode();

            // 遍历Dify返回的会话数组
            for (JsonNode conversation : conversationsArray) {
                String conversationId = conversation.get("id").asText();

                // 检查此会话ID是否在数据库中有记录
                if (conversionIdToClassIdMap.containsKey(conversationId)) {
                    // 将class_id添加到会话数据中
                    ((ObjectNode) conversation).put("class_id", conversionIdToClassIdMap.get(conversationId));

                    // 将匹配的会话添加到新数组
                    filteredArray.add(conversation);
                }
            }

            // 替换原始响应中的会话数组
            ((ObjectNode) difyResponseJson).set("data", filteredArray);

            // 更新has_more字段
            ((ObjectNode) difyResponseJson).put("has_more", filteredArray.size() > 0 && difyResponseJson.get("has_more").asBoolean());

            // 返回修改后的响应
            return objectMapper.writeValueAsString(difyResponseJson);

        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }


    // 删除会话
    @PostMapping("/deleteConversation")
    @PreAuthorize("@ss.hasPermi('deepSeek:deleteConversation:remove')")
    public AjaxResult deleteConversation(@RequestBody DeleteConversationRequest request) {
        try {
            String conversationId = request.getConversationId();
            String result = deepSeekApiService.deleteConversation(conversationId, request.getUser());
            return AjaxResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("Error: " + e.getMessage());
        }
    }

    // 会话重命名
    @PostMapping("/renameConversation")
    @PreAuthorize("@ss.hasPermi('deepSeek:renameConversation:edit')")
    public AjaxResult renameConversation(@RequestBody RenameConversationRequest request) {
        try {
            String result = deepSeekApiService.renameConversation(request.getConversationId(), request.getUser(), request.getNewName(), request.isAutoGenerate());
            return AjaxResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("Error: " + e.getMessage());
        }
    }

    // 语音转文字
    @PostMapping("/audioToText")
    public String audioToText(@RequestBody AudioToTextRequest request) {
        try {
            return deepSeekApiService.audioToText(request.getUser(), request.getFilePath());
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 文字转语音
    @PostMapping("/textToAudio")
    public String textToAudio(@RequestBody TextToAudioRequest request) {
        try {
            return deepSeekApiService.textToAudio(request.getUser(), request.getText());
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}
